package com.cykj.admin.service.impl;

import com.cykj.admin.mapper.JobMapper;
import com.cykj.admin.service.IJobService;
import com.cykj.admin.vo.JobVO;
import com.cykj.common.dto.ResponseDTO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @BelongsProject:@BelonqsPackage:com.cykj.admin.service.impl
 * @Author:jiangna
 * @CreateTime:2025-08-21 10:32
 */
@Service
public class JobServiceImpl implements IJobService {
    @Autowired
    private JobMapper jobMapper;

    @Override
    public ResponseDTO selectByJob(JobVO jobVO) {
        PageInfo<JobVO> page;
        //开启分页
        PageHelper.startPage(jobVO.getCurrentPage(), jobVO.getPageSize());
        List<JobVO> jobList = jobMapper.selectByJob(jobVO);
        System.out.println("list: " + jobList);
        page = new PageInfo<>(jobList);
        if (page.getTotal() < page.getPageSize() && jobList.size() == 0 && page.getTotal() > 0) {
            jobVO.setCurrentPage(1);
            PageHelper.startPage(jobVO.getCurrentPage(), jobVO.getPageSize());
            List<JobVO> jobList2 = jobMapper.selectByJob(jobVO);
            page = new PageInfo<>(jobList2);
        }
        return ResponseDTO.success(page);
    }

    /**
    * @Description: 修改职位
    * @Param: [jobVO]
    * @return: com.cykj.common.dto.ResponseDTO
    */
    @Override
    public ResponseDTO updateByJob(JobVO jobVO) {
        int result = jobMapper.updateByJob(jobVO);
        if (result > 0) {
            return ResponseDTO.success("修改职位信息成功");
        }
        return ResponseDTO.error("修改职位信息失败");
    }

    /**
    * @Description: 添加职位
    * @Param: [jobVO]
    * @return: com.cykj.common.dto.ResponseDTO
    */
    @Override
    public ResponseDTO addByJob(JobVO jobVO) {
        //1.查询职位类型
        String typeName = jobVO.getTypeName(); // 提取职位类别名称
        String jobName = jobVO.getJobName();
        String jobInfo = jobVO.getJobInfo();
        Integer typeId = jobMapper.selectTypeIdByName(typeName);
        // 2. 如果类型不存在，先新增类型再获取 ID
        if (typeId == null || typeId == 0 ) {
            //插入jobtype,并获取该typeName的id
            int result =  jobMapper.insertJobTypeName(jobVO);
            if(result > 0){
                typeId=jobVO.getTypeId();
            }
        }
        int result1 = jobMapper.insertJobType(jobName, jobInfo, typeId);
        if (result1 > 0) {
            return ResponseDTO.success(result1);
        }
        return ResponseDTO.error("职业新增失败");
    }

    /**
    * @Description: 拉黑该职位
    * @Param: [jobVO]
    * @return: com.cykj.common.dto.ResponseDTO
    */
    @Override
    public ResponseDTO deleteJob(JobVO jobVO) {
        int result = jobMapper.deleteJob(jobVO);
        if (result > 0) {
            return ResponseDTO.success(result);
        }
        return ResponseDTO.error("删除职位失败");
    }
}
